package com.shiroha.video.service.impl;

import com.shiroha.video.jellyfin.client.response.MediaResponse;
import com.shiroha.video.pojo.Work;
import com.shiroha.video.pojo.dto.WorkMetaData;
import com.shiroha.video.service.IJellyfinService;
import com.shiroha.video.service.IWorkService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AsyncService {
    private final IJellyfinService jellyfinService;
    private final IWorkService workService;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Autowired
    public AsyncService(IJellyfinService jellyfinService, @Lazy IWorkService workService) {
        this.jellyfinService = jellyfinService;
        this.workService = workService;
    }

    @Async
    public void delayedUpdate(@NonNull Work work, @NonNull WorkMetaData workMetaData) {
        log.info("开始延时更新操作，作品ID: {}", work.getId());
        scheduler.schedule(() -> {
            try {
                MediaResponse response = jellyfinService.getMediaResponse(workMetaData);
                work.setCoverUrl(response.getCoverUrl());
                work.setPlayUrl(response.getPlayUrl());
                workService.updateById(work);
                log.info("延时更新操作完成，作品ID: {}", work.getId());
            } catch (Exception e) {
                log.error("延时更新操作失败，作品ID: {}", work.getId(), e);
                workService.removeById(work.getId());
            }
        }, 1, TimeUnit.MINUTES); // 延时 1 分钟
    }
}